package dealhandler;

import java.util.HashMap;
import java.util.Map;

import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.util.CharsetUtil;

/**
 * 枚举类，枚举所有的请求地址响应
 * 
 * @author KK
 *
 */
public enum ControllerEnum {
	Default("/") {
		@Override
		public String apply(String url, FullHttpRequest msg) {
			return ControllerAider.dealUrldefault(url, msg, getDatas());
		}
	},
	URL1("/hi") {
		@Override
		public String apply(String url, FullHttpRequest msg) {
			return ControllerAider.dealUrlhi(url, msg, getDatas());
		}
	},
	URL2("/love") {
		@Override
		public String apply(String url, FullHttpRequest msg) {
			return ControllerAider.dealUrllove(url, msg, getDatas());
		}
	},
	URL3("/gettest") {
		@Override
		public String apply(String url, FullHttpRequest msg) {
			return ControllerAider.dealUrlGetTest(url, msg, getDatas());
		}
	},
	URL4("/posttest") {
		@Override
		public String apply(String url, FullHttpRequest msg) {
			return ControllerAider.dealUrlPostTest(url, msg, getDatas());
		}
	},
	URL5("/headerstest") {
		@Override
		public String apply(String url, FullHttpRequest msg) {
			return ControllerAider.dealUrlHeadersTest(url, msg, getDatas());
		}
	};

	public abstract String apply(String url, FullHttpRequest msg);

	private String url;
	private Map<String, String> datas = new HashMap<String, String>();

	ControllerEnum(String url) {
		this.url = url.toUpperCase();
	}

	public Map<String, String> getDatas() {
		return datas;
	}

	private void setDatas(Map<String, String> datas) {
		this.datas = datas;
	}

	public String getUrL() {
		return url;
	}

	public static ControllerEnum getDataTypeByStr(String url, FullHttpRequest msg) {
		if (url != null && !url.isEmpty()) {
			Map<String, String> datastemp = new HashMap<>();
			String method = msg.method().name().toUpperCase();
			int location = url.indexOf("?");
			if (location > 0) {
				String urltemp = url.substring(0, location);//获取请求地址
				if (method.equals("GET")) {
					String GetData = url.substring(location + 1);//获取GET参数
					datastemp = getUrldata(GetData);
				}
				url = urltemp;
			} else if (method.equals("POST")) {
				String PostData = msg.content().toString(CharsetUtil.UTF_8);
				datastemp = getUrldata(PostData);
			}
			for (ControllerEnum Controller : values()) {
				if (Controller.getUrL().equalsIgnoreCase(url)) {
					Controller.setDatas(datastemp);
					return Controller;
				}
			}
		}
		return ControllerEnum.Default;
	}

	private static Map<String, String> getUrldata(String datas) {
		Map<String, String> datastemp = new HashMap<>();
		String[] datastrs = datas.split("&");
		for (int i = 0; i < datastrs.length; i++) {
			String[] datatemps = datastrs[i].split("=");
			if (datatemps.length == 2) {
				datastemp.put(datatemps[0], datatemps[1]);
			}
		}
		return datastemp;
	}
}
